package com.ruoyi.distributionRelation.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.ruoyi.distributionRelation.service.IDistributionRelationCacheService;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 分销关系缓存服务实现类
 * 使用Redis存储临时分销关系
 */
@Service
public class DistributionRelationCacheServiceImpl implements IDistributionRelationCacheService {

    private static final String REDIS_KEY_PREFIX = "distribution:temp:relation:";
    private static final int DEFAULT_EXPIRE_MINUTES = 30; // 默认30分钟过期

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public void cacheTemporaryRelation(Long userId, Long distributorId, Long goodsId, int expireMinutes) {
        String key = REDIS_KEY_PREFIX + userId;
        Map<String, Object> relationData = new HashMap<>();
        relationData.put("distributorId", distributorId);
        relationData.put("goodsId", goodsId);
        relationData.put("cacheTime", System.currentTimeMillis());

        if (expireMinutes <= 0) {
            expireMinutes = DEFAULT_EXPIRE_MINUTES;
        }

        redisTemplate.opsForValue().set(key, relationData, expireMinutes, TimeUnit.MINUTES);
    }

    @Override
    public Map<String, Object> getTemporaryRelation(Long userId) {
        String key = REDIS_KEY_PREFIX + userId;
        Object data = redisTemplate.opsForValue().get(key);

        if (data instanceof Map) {
            return (Map<String, Object>) data;
        }
        return null;
    }

    @Override
    public void removeTemporaryRelation(Long userId) {
        String key = REDIS_KEY_PREFIX + userId;
        redisTemplate.delete(key);
    }

    @Override
    public boolean hasTemporaryRelation(Long userId) {
        String key = REDIS_KEY_PREFIX + userId;
        return Boolean.TRUE.equals(redisTemplate.hasKey(key));
    }
}